package com.gift.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gift.auto.JSONAuthentication;
import com.gift.entity.*;
import com.gift.mapper.*;
import com.gift.response.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gift
 * @since 2022-03-23
 */
@RestController
@RequestMapping("/lpc-order")
public class LpcOrderController extends JSONAuthentication {
    @Autowired
    LpcOrderMapper lpcOrderMapper;
    @Autowired
    GiUserMapper giUserMapper;
    @Autowired
    LpcUserMapper lpcUserMapper;
    @Autowired
    LpcTypeMapper lpcTypeMapper;
    @Autowired
    GiLpcMapper giLpcMapper;

    @ApiOperation(value = "用户购买礼品册")
    @PostMapping("/add")
    public void addCar(HttpServletRequest request, HttpServletResponse response, @RequestParam("userId") int  userId,@RequestParam("lpcId") int lpcId) throws Exception {
        GiUser giUser = giUserMapper.selectById(userId);
        int balance=giUser.getBalance();
        GiLpc giLpc = giLpcMapper.selectById(lpcId);
        LpcType lpcType = lpcTypeMapper.selectById(giLpc.getTypeId());
        int price=lpcType.getPrice();
        if(balance-price>0){
            LpcOrder lpcOrder=new LpcOrder();
            lpcOrder.setUserId(userId);
            lpcOrder.setLpcId(lpcId);
            Date date=new Date();
            Timestamp timestamp=new Timestamp(date.getTime());
            lpcOrder.setCreatTime(timestamp);
            LpcUser lpcUser=new LpcUser();
            lpcUser.setLpcId(lpcId);
            lpcUser.setUserId(userId);
            giUser.setBalance(balance-price);
            giLpc.setStatus("已售出");
            lpcType.setNum(lpcType.getNum()+1);
            if(lpcOrderMapper.insert(lpcOrder)>0&&lpcUserMapper.insert(lpcUser)>0&&giUserMapper.updateById(giUser)>0&&giLpcMapper.updateById(giLpc)>0&&lpcTypeMapper.updateById(lpcType)>0){
                Result ok = Result.ok();
                this.WriteJSON(request, response, ok);
            }else{
                Result error = Result.error();
                this.WriteJSON(request, response, error);
            }
        }else{
            Result error = Result.error().message("余额不足");
            this.WriteJSON(request, response, error);
        }
    }


}

